package com.chw.common.interceptors;

import com.chw.model.Org;
import com.chw.service.OrgService;
import com.chw.service.impl.OrgServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Component
public class KuaYu implements HandlerInterceptor {
    @Autowired
    private OrgService orgService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  throws Exception{

        // 处理跨域的  response设置运行跨域
        // 获取请求域
        String origin=request.getHeader("Origin");
        //获取访问的ip地址
        String ip=request.getRemoteAddr();
        //获取白名单
        List<Org>orgs=  orgService.queryOrgByisDel();
        //判断后赋值
        boolean flan=false;
        for (int i = 0; i < orgs.size(); i++) {
            if(ip.equals(orgs.get(i).getIp())){
                flan=true;
                break;
            }
        }
        //判断是否为true
        if (flan==true){//true
            if (origin!=null){
                //设置允许跨域
                response.setHeader("Access-Control-Allow-Origin",origin);

            }
        }else {//flan为false
            //返回错误信息 设置为json格式
            response.setContentType("application/json");
            //设置编码
            response.setCharacterEncoding("utf-8");
            //获取写的流
            PrintWriter writer=null;
            try {
                writer=response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.write("{\"code\":3000,\"msg\":\""+ip+"不在白名单内，想用，微信转账20000块\"}");
            writer.close();
        }

//        response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
        return flan;
    }
}
